package it.orma.iridehr.service;

import it.orma.iridehr.repository.RicercaRepository;
import it.orma.iridehr.services.helper.RisultatoRicerca;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.WebAttributes;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;


public class AuthSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
    @Override
    protected String determineTargetUrl(HttpServletRequest request, HttpServletResponse response) {
        // Get the role of logged in user
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String role = auth.getAuthorities().toString();
        UserDetails currentUserDetails = (UserDetails) auth.getPrincipal();
        String targetUrl = "";
        
        WebApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
        RicercaService userService = (RicercaService) appContext.getBean("ricercaService");
        
        Long res = userService.ricercaCandidatoSuDb(currentUserDetails.getUsername());
        
        if(role.contains("USER")) {
            targetUrl = "/candidato?idCandidato="+res+"&loginCandidato=userLogin";
        } else if(role.contains("ADMIN")) {
            targetUrl = "/ricerca?execution=e1s1";
        }
        return targetUrl;
    }
}

